﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.storage.productarrange
{
    public partial class storageadj_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty1 = "0", Total_qty2 = "0";

        private void getTotal()
        {
            Total_qty1 = ((storageadj_product_class)Session["storageadj_out"]).Total_qty1.ToString();
            Total_qty2 = ((storageadj_product_class)Session["storageadj_out"]).Total_qty2.ToString();
        }

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("id");
            dtList.Columns.Add("areaname_out");
            dtList.Columns.Add("storagename_out");
            dtList.Columns.Add("areaname_in");
            dtList.Columns.Add("storagename_in");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty1");
            dtList.Columns.Add("qty2");

            DataTable dtData = ((storageadj_product_class)Session["storageadj_out"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["id"] = dr["id"].ToString();
                drnew["areaname_out"] = dr["areaname_out"].ToString();
                drnew["storagename_out"] = dr["storagename_out"].ToString();
                drnew["areaname_in"] = dr["areaname_in"].ToString();
                drnew["storagename_in"] = dr["storagename_in"].ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty1"] = dr["qty1"].ToString();
                drnew["qty2"] = dr["qty2"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        private void Reset()
        {
            uc_from_warehouse.Reset();

            uc_from_area_out.setArea("");
            uc_from_storageset_out.SetByWarehouse("");

            uc_from_area_in.setArea("");
            uc_from_storageset_in.SetByWarehouse("");
            
            txt_remark.Text = "";

            ((storageadj_product_class)Session["storageadj_out"]).Reset();

            getTotal();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    ((storageadj_product_class)Session["storageadj_out"]).Reset();
                }
                catch
                {
                    Session.Add("storageadj_out", new storageadj_product_class(Session["connectionString"].ToString()));
                }

                Bind();

                getTotal();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                uc_from_area_out.setArea("");
                uc_from_storageset_out.SetByWarehouse("");

                uc_from_area_in.setArea("");
                uc_from_storageset_in.SetByWarehouse("");
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            edowork.com.Model.Library_adjInfo Library_adjInfo = new Library_adjInfo();
            edowork.com.Model.Library_adj_detailInfo Library_adj_detailInfo = new Library_adj_detailInfo();

            Library_adjInfo.Billdate = uc_billdate.getValue();
            Library_adjInfo.Warehouseid = uc_from_warehouse.getValue();
            Library_adjInfo.Remark = txt_remark.Text.Trim();
            Library_adjInfo.Checkuserid = "";
            Library_adjInfo.Checkstu = "0";
            Library_adjInfo.Checkdate = "";
            Library_adjInfo.M_stu = "0";
            Library_adjInfo.M_ID = "";
            Library_adjInfo.M_date = "";
            Library_adjInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");
            Library_adjInfo.Userid = Session["userid"].ToString();

            if (String.IsNullOrEmpty(Library_adjInfo.Billdate))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入开单日期");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(Library_adjInfo.Warehouseid))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择调整仓库");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (((storageadj_product_class)Session["storageadj_out"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入调整的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //取得调整单编码
            Library_adjInfo.Ljid = SysID.SCR_LJID(Session["connectionString"].ToString(), ref alert_msg);
            Library_adj_detailInfo.Ljid = Library_adjInfo.Ljid;

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(Library_adjInfo.Billdate).ToString("yyyy"), DateTime.Parse(Library_adjInfo.Billdate).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查是否存在盘点单
                sql = String.Format("select csid from check_stock where warehouseid='{0}' and checkstu='0'", Library_adjInfo.Warehouseid);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前仓库正在盘点，不能进行出入库操作。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //保存入Library_adj表
                sql = String.Format(Library_adjInfo.SQL_Insert(), Library_adjInfo.Ljid, Library_adjInfo.Billdate, Library_adjInfo.Warehouseid, Library_adjInfo.Remark, Library_adjInfo.Userid, Library_adjInfo.Sysdate,
                                                                  Library_adjInfo.Checkuserid, Library_adjInfo.Checkdate, Library_adjInfo.Checkstu, Library_adjInfo.Checkremark,
                                                                  Library_adjInfo.M_stu, Library_adjInfo.M_date, Library_adjInfo.M_ID);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                DataTable dtData = ((storageadj_product_class)Session["storageadj_out"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入billsdetail表
                    sql = String.Format(Library_adj_detailInfo.SQL_Insert(), Library_adj_detailInfo.Ljid,
                                        dr["areaid_out"].ToString(), dr["Storageid_out"].ToString(),
                                        dr["areaid_in"].ToString(), dr["storageid_in"].ToString(),
                                        dr["productcode"].ToString(), dr["qty1"].ToString());

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            Reset();

            Bind();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();

            Bind();
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/storage/productarrange/storageadj.aspx";

            Response.Redirect(url);
        }

        //添加产品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string areaid_out = uc_from_area_out.getValue();
            string storageid_out = uc_from_storageset_out.getValue();

            string areaid_in = uc_from_area_in.getValue();
            string storageid_in = uc_from_storageset_in.getValue();

            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();

            if (((storageadj_product_class)Session["storageadj_out"]).Add(areaid_out, storageid_out, areaid_in, storageid_in, productu_code, qty, "0", ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";

            Bind();

            getTotal();

        }

        //删除货品
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((storageadj_product_class)Session["storageadj_out"]).Delect(id);

                        //查询
                        Bind();

                        getTotal();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);


                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }

        //调整仓库的选择
        protected void uc_from_warehouse_OnbtSelect_Click(object sender, EventArgs e)
        {
            string warehouseid = uc_from_warehouse.getValue();

            uc_from_area_out.setArea(warehouseid);
            uc_from_storageset_out.SetByWarehouse(warehouseid);

            uc_from_area_in.setArea(warehouseid);
            uc_from_storageset_in.SetByWarehouse(warehouseid);
        }

        //库位的选择
        protected void uc_from_area_out_OnbtSelect_Click(object sender, EventArgs e)
        {
            string areadid = uc_from_area_out.getValue();

            if (String.IsNullOrEmpty(areadid))
            {
                return;
            }

            uc_from_storageset_out.setStorage(areadid);
        }

        //库位的选择
        protected void uc_from_area_in_OnbtSelect_Click(object sender, EventArgs e)
        {
            string areadid = uc_from_area_in.getValue();

            if (String.IsNullOrEmpty(areadid))
            {
                return;
            }

            uc_from_storageset_in.setStorage(areadid);
        }
    }
}